<template>
  <a-card :bordered="false">
    <!-- 网上投标 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24"></a-row>
      </a-form>
    </div>
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="bidSectionId"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <template slot="downloadEndTime" slot-scope="text,record">
             <j-upload  :buttonVisible="false"  :disabled="true" v-model="record.downloadAttachment"  v-if="downloadAttachmentFlag(record)"></j-upload>
        </template>
        <template slot="configFlag" slot-scope="text, record">
          <a @click="doDownloadModal(record)"  v-if="record.tempStatus == 2">下载</a>
        </template>
        <span slot="action" slot-scope="text, record">
          <template v-if="record.exTenderList != null">
            <!-- 如果未完成上传且未超过截止时间，显示“上传投标文件” -->
            <a @click="doUploadModel(record)" v-if="!record.uploadCompleted && !isPastTime(record.bidOpeningTime)">上传投标文件</a>
            <!-- 如果未完成上传,只是下载了，且已超过截止时间，显示“已开标” -->
            <span v-else-if="!record.uploadCompleted && isPastTime(record.bidOpeningTime)">已开标</span>
            <!-- 如果已完成上传，显示“模拟解密”和“撤回投标文件” -->
            <template v-else>
              <a-row>
                <!-- <a @click="doShowResult(record)">查看回执单</a> <a-divider type="vertical" /> -->
                <a @click="doDecrypt(record)">模拟解密</a>
              </a-row>
              <a-row v-if="!isPastTime(record.bidOpeningTime)">
                <a-popconfirm title="确定撤回投标文件吗?" @confirm="() => doRevoke(record)">
                  <a>撤回投标文件</a>
                </a-popconfirm>
              </a-row>
            </template>
          </template>
        </span>
      </a-table>
    </div>

    <a-modal
      ref="refUploadModel"
      :title="modelTitle"
      :width="800"
      :visible="visible"
      :closable="true"
      :maskClosable="true"
    >
      <template slot="footer">
        <a-button @click="close">关闭</a-button>
        <a-button type="primary" @click="departOk" :loading="departLoading">确认</a-button>
      </template>
      <a-row style="font-size: 14px; letter-spacing: 2px; line-height: 30px">
        <a-row>
          <a-col :span="8" style="font-weight: bold; font-size: 16px; line-height: 50px">操作提示</a-col>
        </a-row>
        <a-row> 1、请您确认要上传的投标文件已经制作完成.</a-row>
        <a-row>
          2、投标即为了递交投标文件(投标文件制作系统生成的名字头xxxxx.tbf]的文件)，若在递交结束前需要修改投标文件，则必须将投标文件撒回才能再次上传(投标或撒标都应在
          递交开始到递交结束时间之间进行).
        </a-row>
        <a-row> 3、上传成功自动签到，请接受交易中心返回给您的接受投标文件回执，若没有收到请及时联系交易中心</a-row>
      </a-row>
      <br />
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="投标文件" :labelCol="{lg: {span: 7}, sm: {span: 7}}"
                             :wrapperCol="{lg: {span: 10}, sm: {span: 17} }" prop="attachment">
            <upload-file v-model="bidFile" :number="1" :text="'上传投标文件'"></upload-file>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-form></a-form>
    </a-modal>

    <a-modal
      title="回执单"
      :width="800"
      :visible="resultVisible"
      :closable="true"
      :maskClosable="true"
      :destroyOnClose="true"
      :footer="null"
      @cancel="handleCancel"
    >
      <a-row style="font-size: 14px; letter-spacing: 2px; line-height: 30px"> 您已经完成投标文件上传操作！</a-row>
    </a-modal>

    <a-modal
      title="解密结果"
      :width="800"
      :visible="decryptVisible"
      :closable="true"
      :maskClosable="true"
      :destroyOnClose="true"
      :footer="null"
      @cancel="decryptClose"
    >
      <a-row style="font-size: 14px; letter-spacing: 2px; line-height: 30px">
        {{ decryptContent }}
      </a-row>
    </a-modal>

    <a-modal
      title="下载"
      :width="800"
      :visible="doDownloadVisible"
      :closable="true"
      :maskClosable="true"
      :destroyOnClose="true"
    >
      <template slot="footer">
        <a-button @click="downloadClose">关闭</a-button>
        <a-button type="primary" @click="downloadOk" :loading="downloadLoading">确认</a-button>
      </template>
      <j-form-container>
        <a-form-model ref="downloadForm" :model="downloadModel" :rules="validatorRules" slot="detail">
          <a-row>
            <a-col :span="24">
              <a-form-model-item label="下载人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="downloadUserName">
                <a-input v-model="downloadModel.downloadUserName" placeholder="请输入下载人员"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="所在企业" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unitName">
                <a-input v-model="downloadModel.unitName" placeholder="所在企业"></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </j-form-container>
    </a-modal>
  </a-card>
</template>

<script>
import '@assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { filterMultiDictText } from '@comp/dict/JDictSelectUtil'
import { getAction, postAction, deleteAction, downloadFile } from '@api/manage'
import UploadFile from '@/views/exProjectInfo/UploadFile.vue'

export default {
  name: 'xmtb',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    UploadFile,
  },
  data () {
    return {
      description: '网上投标',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '标段编号',
          align: 'center',
          dataIndex: 'bidSectionCode',
        },
        {
          title: '标段名称',
          align: 'center',
          dataIndex: 'bidSectionName',
        },
        {
          title: '标段描述',
          align: 'center',
          dataIndex: 'bidSectionContent',
        },
        {
          title: '下载招标文件',
          align: 'center',
          dataIndex: 'configFlag',
          scopedSlots: { customRender: 'configFlag' },
        },
        {
          title: '下载招标附件',
          align: 'center',
          dataIndex: 'downloadEndTime',
          scopedSlots: { customRender: 'downloadEndTime' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center', 
          width: 247,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/exProject/exProject/queryExSectionByMainId?id=',
        queryByProjectId: '/exTender/exTenderList/queryExSectionByMainId?projectId=',
        exTenderListUpdate: '/exTender/exTenderList/edit', //投标
        checkFile: '/exTender/exTenderList/checkFile', //校验投标文件
        desTenderFile: 'exTender/exTenderList/preDesTenderFile', //模拟解密
      },
      dictOptions: {},
      superFieldList: [],
      disableMixinCreated: true,
      projectId: null,
      visible: false,
      modelTitle: '上传投标文件',
      selectRow: null,
      bidFile: '', //投标文件
      resultVisible: false,
      doDownloadVisible: false,
      decryptVisible: false,
      decryptContent: '',
      downloadModel: {},
      validatorRules: {
        downloadUserName: [{ required: true, message: '请输入下载人员!' }],
        unitName: [{ required: true, message: '请输入所在企业!' }],
      },
      loading: false,
      downloadLoading: false,
      departLoading: false,
    }
  },
  created () {
    this.getSuperFieldList()
    this.projectId = this.$route.query.projectId
    this.projectName = this.$route.query.projectName
    this.queryList()
    //初始化字典配置 在自己页面定义
    this.initDictConfig()
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    isPastTime(timeStr) {
    // 统一处理日期分隔符和日期时间分隔符

    const inputDate = new Date(timeStr+ 'Z');
    console.log("时间",inputDate.getTime());
    console.log("当前时间",Date.now());

    // 检查日期是否有效
    if (isNaN(inputDate.getTime())) {
        throw new Error('无效的时间格式');
    }

      return Date.now() > inputDate.getTime();
},
    doDownloadModal (record) {
      this.selectRow = record
      this.doDownloadVisible = true
    },
    downloadOk () {
      const that = this
      // 触发表单验证
      this.$refs.downloadForm.validate((valid) => {
        if (valid) {
          that.downloadLoading = true
          let param = {
            sectionId: this.selectRow.id,
            downloadUserName: that.downloadModel.downloadUserName,
            unitName: that.downloadModel.unitName,
          }
          var exportUrl = '/exTenderFileClariModi/exTenderFileClariModi/download/zbFile'
          downloadFile(exportUrl, 'aa.zip', param, 'get').then(() => {
            that.downloadClose()
            that.queryList()
          }).finally(() => {
            that.downloadLoading = false
          })

        }
      })
    },
    downloadClose () {
      this.downloadModel.downloadUserName = ''
      this.downloadModel.unitName = ''
      this.doDownloadVisible = false
    },
    doUploadModel (record) {
      this.selectRow = record
      this.modelTitle = record.bidSectionName
      this.bidFile = ''
      this.visible = true
    },
    close () {
      this.visible = false
    },
    departOk () {
      var that = this
      if (that.bidFile == '' || that.bidFile == undefined || that.bidFile == null) {
        that.$message.warning('请上传文件')
        return
      }
      that.checkFile()
    },
    checkFile () {
      var that = this
      this.departLoading = true
      getAction(this.url.checkFile, { id: that.selectRow.exTenderList.id })
        .then((res) => {
          if (res.success) {
            that.uploadOk()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.departLoading = false
        })
    },
    uploadOk () {
      const that = this
      var param = { id: that.selectRow.exTenderList.id, attachment: that.bidFile }
      that.departLoading = true
      postAction(this.url.exTenderListUpdate, param).then((res) => {
        if (res.success) {
          that.$message.success('操作成功')
          that.queryList()
          that.visible = false
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 查询 exTenderFileClariModi 的发布状态
    queryExTenderFileClariModiStatus(sectionId) {
      return getAction(`/exTenderFileClariModi/exTenderFileClariModi/list`, { sectionId });
    },
    doShowResult (record) {
      this.resultVisible = true
    },
    handleCancel () {
      this.resultVisible = false
    },
    doRevoke (record) {
      //撤回
      var that = this
      postAction(that.url.exTenderListUpdate, { id: record.exTenderList.id, attachment: '' }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.queryList()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    decryptClose () {
      this.decryptVisible = false
    },
    queryList() {
      getAction(this.url.queryByProjectId + this.projectId)
        .then((res) => {
          if (res.success) {
            const promises = res.result.map(item => {
              console.log("当前 item.id (sectionId):", item.id); // 这里面的id即为标段ID，输出当前处理的标段ID
              return this.queryExTenderFileClariModiStatus(item.id).then(statusRes => {
                if (statusRes.success) {
                  console.log("查询成功，返回数据:", statusRes); // 输出查询成功的返回数据
                  const status = statusRes.result.records[0]?.status || 0; // 提取 查询结果里面records对象的status
                  const downloadEndTime = statusRes.result.records[0]?.downloadEndTime || '';
                  const downloadAttachment = statusRes.result.records[0]?.downloadAttachment || '';
                  console.log("查询到的 downloadEndTime:", downloadEndTime); // 输出查询到的 status

                  // 动态绑定 tempStatus 并输出
                  const updatedItem = {
                    ...item,
                    tempStatus: status,
                    downloadEndTime:downloadEndTime,
                    downloadAttachment:downloadAttachment
                  };
                  console.log("查询到的 tempStatus:", updatedItem.tempStatus); // 查看是否绑定成功 tempStatus
                  return updatedItem;
                } else {
                  console.warn("查询失败，返回信息:", statusRes.message); // 输出查询失败的返回信息
                  return { ...item, tempStatus: 0 }; // 如果查询失败，设置默认值
                }
              }).catch(error => {
                console.error("查询异常:", error); // 捕获并输出异常信息
                return { ...item, tempStatus: 0 }; // 异常情况下设置默认值
              });
            });

            // 等待所有查询完成
            Promise.all(promises).then(updatedData => {
              this.dataSource = updatedData;
            });
          } else {
            this.$message.warning(res.message);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    initDictConfig () {},
    getSuperFieldList () {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'bidSectionName', text: '标段名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'bidSectionContent', text: '标段描述', dictCode: '' })
      this.superFieldList = fieldList
    },
    doDecrypt (record) {
      var that = this
      var tenderListId = record.exTenderList.id
      this.loading = true
      postAction(this.url.desTenderFile, { tenderListId: tenderListId, certKey: '123456' })
        .then((res) => {
         /* that.decryptContent = res.message
          that.decryptVisible = true*/
          this.$message.success('解密成功');
        })
        .finally(() => {
          this.loading = false
        })
    },
    downloadAttachmentFlag (record) {
     // return true;//todo 先注释掉
      if (!record) {
        return false
      }
      if (!record.downloadEndTime) {
        return false
      }
      let downloadEndTime = new Date(record.downloadEndTime)
      if (downloadEndTime > new Date()) {
        return true
      }
      return false
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
